<?php
/**
 * Created by 胡祥能 on 2018/1/4.
 *  email：huxiangneng@jiuletech.com
 */

namespace App\Http\Controllers\Admin;

use App\User;
use Gregwar\Captcha\CaptchaBuilder;
use Illuminate\Http\Request;
use Validator;
use Log;

class LoginController extends DefaultController
{
    /**用户登录
     * @param Request $request
     * @return mixed
     */
    public function login(Request $request) {
        if($request->method() == 'GET') {
            return view('admin.login');
        }else{
            $validator = Validator::make($request->all(), [
                'username' => 'bail|required|max:50',
                'pwd' => 'bail|required|max:20',
            ]);
            $username = $request->input('username');
            $pwd = $request->input('pwd');

            $user = User::where('name', $username)->first();

            if(!$user){
                $validator->errors()->add('username', '该用户不存在');
                return back()->withInput()->withErrors($validator);
            }elseif($user->password != md5($pwd)){
                $validator->errors()->add('pwd', '密码错误');
                return back()->withInput()->withErrors($validator);
            }elseif($user->status == 0){
                $validator->errors()->add('username', '该用户已禁用');
                return back()->withInput()->withErrors($validator);
            }else{
                User::where('name', $username)->update([
                    'last_login' => date('Y-m-d H:i:s')
                ]);
                // 如果登录用户的权限发生变化时，session里面的角色数据也要变
                $user->roles = $user->roles()->get()->toArray();//查出该用户所有角色

                $request->session()->put(User::SESSION_KEY, $user);
            }

            return redirect()->route('dashboard');
        }
    }

    /**注销
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function logout(Request $request) {
        $request->session()->forget(User::SESSION_KEY);
        return redirect('/login');
    }

    public function generateCaptcha(Request $request) {
        header('Content-type: image/jpeg');
        $builder = new CaptchaBuilder();
        $builder->build();
        session(['login_captcha'=> $builder->getPhrase()]);
        $builder->output();
        return;
    }

    public function updatePwd(Request $request) {
        if($request->method() == 'GET'){
            return view('admin.user.updatepwd');
        }else{

        }
    }

    public function forgetPwd(Request $request)
    {
        return view('admin.forgetpwd');
    }
}